package com.example.batterynotification;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;



public class BatteryReceiverForeground extends BroadcastReceiver {
	private ImageView batteryStatus;
	private ImageView chargeSign ;
	private static String sHighRemainingTime;
	private static String sLowRemainingTime;	
	private static TextView remainingTime;
	private TextView batteryLevel;
	private TextView powerSource;
	private TextView batteryState;
	private static String sBatteryStatus;	
	private static int highNotificationLevel;
	private static  int lowNotificationLevel;
	private static int    level ;
	@Override
	public void onReceive(final Context context, final Intent intent) {
			Log.i("LC", "OnReceieve");
		 ((Activity)context).runOnUiThread(new Runnable()
         {
             public void run()
             { 
            	 level  = intent.getIntExtra("level", 0);            	 
      //      	 String sBatteryHealth  = getBatteryHealth( intent);
            	 String sPlugType       = getPlugTypeString(intent);
        //    	 String sBatteryTemp    = getBatteryTemp(intent);
            	 sBatteryStatus = getBatteryState(intent);
        //    	 String sBatteryVoltage = getBatteryVoltage(intent);
            	 sHighRemainingTime  =null ;
            	 
        //    	 BatteryReceiverForegroundResources.setBatteryIntent(intent);
            	 
			  highNotificationLevel = Preferences.getIntPreferences("prefHighBatteryLevel");
			  lowNotificationLevel  =Preferences.getIntPreferences("prefLowhBatteryLevel"); 			  


				
            	 BatteryReceiverForegroundResources.SetBatteryLevel(Integer.toString(level) + " %"); 
                
            	 if(Preferences.getBoolPreferences("isMainActivityActive"))
            	 {
              chargeSign = (ImageView)((Activity) context).findViewById(R.id.chargesign);
              batteryLevel = (TextView) (((Activity) context).findViewById(R.id.textfield));
   	//		  TextView batteryHealth = (TextView) (((Activity) context).findViewById(R.id.batteryhealth));             
   	//		  TextView batteryTemp =(TextView) (((Activity) context).findViewById(R.id.batterytemp));             
              powerSource  = (TextView) (((Activity) context).findViewById(R.id.powersource)); 
			  batteryState= (TextView) (((Activity) context).findViewById(R.id.batterystate)); 			  
	//		  TextView batteryVoltage= (TextView) (((Activity) context).findViewById(R.id.batteryvoltage)); 
			   remainingTime= (TextView) (((Activity) context).findViewById(R.id.remainingtime));
//			   if(sBatteryStatus.equals("Charging") )
////			   	ShowACChargingTime();  	
//			   else if(sBatteryStatus.equals("Discharging"))
//			   {
////			    ShowDischargingTime();
//			   Log.i("TI", "the battery is now discharging");
//			   }

			  Log.i("LC", "GOT TEXT");
   			  //Set TextView with text
			  toggleChargingSign(intent);
   			  batteryLevel.setText("Battery Level: " + Integer.toString(level) + "%");
   		//	  batteryHealth.setText("Battery Health: " + sBatteryHealth);
   		//	  batteryTemp.setText("Battery Temperature: " + sBatteryTemp );           
   			  powerSource.setText("Charging source: " + sPlugType); 
              batteryState.setText("Battery State: " + sBatteryStatus );  
       //       batteryVoltage.setText("Battery Voltage: " + sBatteryVoltage + " mV");  

              Log.i("LC", "out");
   			  changeLevelImage(intent,context);
   			Log.i("LC", "CHANGE LEVEL IMAGE ");
            	 }
             }
         });	 
	}

	private String getBatteryState(Intent intent)
	{
		String batteryStatus = "Unknown";
		int status=intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
	switch (status)
	{
	case BatteryManager.BATTERY_STATUS_CHARGING:
		batteryStatus= "Charging";
		break;	
		
	case BatteryManager.BATTERY_STATUS_DISCHARGING:
		batteryStatus="Discharging";
		break;
		
	case BatteryManager.BATTERY_STATUS_FULL:
		batteryStatus="Battery Full";
		break;
		
	case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
		batteryStatus = "Not Charging";		
		break;	
		
	case BatteryManager.BATTERY_STATUS_UNKNOWN:
		batteryStatus ="Unknown";	
		break;

	
	}
	BatteryReceiverForegroundResources.SetBatteryState(batteryStatus);
		return batteryStatus;	
	}	
	
	private void toggleChargingSign(Intent intent)
	{

		int status=intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
		if(status == BatteryManager.BATTERY_STATUS_CHARGING)
			chargeSign.setVisibility(View.VISIBLE);
		else
			chargeSign.setVisibility(View.INVISIBLE);
	}
	
	private String getBatteryHealth(Intent intent)
	{
	    int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
	    String healthState = "unknown";
	    switch (health) {
		case BatteryManager.BATTERY_HEALTH_DEAD:
			healthState="Dead";
			break;
		case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
			healthState="Over Voltage";
			break;
		case BatteryManager.BATTERY_HEALTH_OVERHEAT:
			healthState="Over Heat";
			break;
		case BatteryManager.BATTERY_HEALTH_GOOD:
			healthState="Good";
			break;
		case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
			healthState="Failure";
			break;
		case BatteryManager.BATTERY_HEALTH_COLD:
			healthState="Cold";
			break;	
		default:
			break;
		}
	    BatteryReceiverForegroundResources.SetBatteryHealth(healthState);
		return healthState;
		
	}
	private String getBatteryTemp(Intent intent)
	{
		int temperature=intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
		BatteryReceiverForegroundResources.SetBatteryTemperature(Integer.toString(temperature) + " °C");		
		return Integer.toString(temperature);
		
	}
	private String getBatteryVoltage(Intent intent)
	{
		int voltage=intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
		BatteryReceiverForegroundResources.SetBatteryVoltage(Integer.toString(voltage) + " mV");				
		return Integer.toString(voltage);		
	}
	private String getPlugTypeString(Intent intent) {
		String plugType = "N/A";
		int plugged = intent.getIntExtra("plugged", -1);
		switch (plugged) {
		case BatteryManager.BATTERY_PLUGGED_AC:
			plugType = "AC";
			break;
		case BatteryManager.BATTERY_PLUGGED_USB:
			plugType = "USB";
			break;
		}
		BatteryReceiverForegroundResources.SetBatteryChargingSource(plugType);
		return plugType;
	}	
	private void changeLevelImage(Intent intent,Context context)
	{
		  int level = intent.getIntExtra("level", 0);
        batteryStatus =(ImageView)((Activity) context).findViewById(R.id.batteryStatus);
        if (level<=5 && level>0)
        	batteryStatus.setImageResource(R.drawable.state5); 
        else if(level<3)
          	batteryStatus.setImageResource(R.drawable.stateempty);
        else if(level>=5 && level<10)
        	batteryStatus.setImageResource(R.drawable.state10);
        else if(level>=10 && level<20)
        	batteryStatus.setImageResource(R.drawable.state20);            
        else if(level>=20 && level<30)
        	batteryStatus.setImageResource(R.drawable.state30);	            	
        else if((level>=30) && level <40)
        	batteryStatus.setImageResource(R.drawable.state40);
        else if((level>=40)&& level<50)
        	batteryStatus.setImageResource(R.drawable.state50);	   
        else if((level>=50)&& level<60)
        	batteryStatus.setImageResource(R.drawable.state60);	
        else if((level>=60)&& level<70)
        	batteryStatus.setImageResource(R.drawable.state70);	
        else if((level>=70)&& level<80)
        	batteryStatus.setImageResource(R.drawable.state80);		
        else if((level>=80)&& level<90)
        	batteryStatus.setImageResource(R.drawable.state90);	 
        else if((level>=90)&& level<=100)
        	batteryStatus.setImageResource(R.drawable.statefull); 
        

	}
	
 
	public static void ShowACChargingTime()
	{
        if( (highNotificationLevel>level) && Preferences.getBoolPreferences("HighSwitch") )
        {
      	  remainingTime.setVisibility(View.VISIBLE);
      	  Log.i("TI","VISibility =View.VISIBLE "); 
			 sHighRemainingTime   =Preferences.getStringPreferences("ChargingTimer");
        	 if(sHighRemainingTime    != null)
        	 {
			 int timer= Integer.parseInt(sHighRemainingTime  );
			 Log.i("TI","ShowACChargingTime Timer=" +timer);
			 int iRemainingtime=timer*(highNotificationLevel-level);
			 Log.i("TI","ShowACChargingTime iRemainingtime=" +iRemainingtime);		 
			 sHighRemainingTime   = Util.MilliSecondsConvert(iRemainingtime);				 
        	 }
        }
        else 
      	  {
      	  remainingTime.setText("");       	
      	  Log.i("TI","Visibilty is View.INVISIBLE");
      	  remainingTime.setVisibility(View.INVISIBLE);
      	  }
        if(sHighRemainingTime != null)
        {
        remainingTime.setText("Remaining Time: about " + sHighRemainingTime );     
        }
        else
        {
      	  remainingTime.setText("Remaining Time: Calculating...");                 	  
        }		
		
	}
	
	  public static void ShowDischargingTime()
	  {
		  
		  Log.i("TI", "Entered ShowDischargingTime");
		  Log.i("TI", "lowNotificationLevel=" + lowNotificationLevel+ "&level"+level);
		  Log.i("TI", "low switch status =" +Preferences.getBoolPreferences("LowSwitch"));
	        if( (lowNotificationLevel<level) && Preferences.getBoolPreferences("LowSwitch") )
	          {
	        	  remainingTime.setVisibility(View.VISIBLE);
	        	  Log.i("TI","VISibility =View.VISIBLE "); 
	        	  sLowRemainingTime   =Preferences.getStringPreferences("DischargingTimer");
	          	 if(sLowRemainingTime    != null)
	          	 {
	  			 int timer= Integer.parseInt(sLowRemainingTime);
	  			 int iRemainingtime=timer*(level-lowNotificationLevel);
	  			sLowRemainingTime  = Util.MilliSecondsConvert(iRemainingtime);			 
	          	 }
	          }
	          else 
	        	  {
	        	  remainingTime.setText("");
	        	  Log.i("TI","Visibilty is View.INVISIBLE");
	        	  remainingTime.setVisibility(View.INVISIBLE);
	        	  }
	          if(sLowRemainingTime != null)
	          {
	          remainingTime.setText("Remaining Time: about " + sLowRemainingTime );     
	          }
	          else
	          {
	        	  remainingTime.setText("Remaining Time: Calculating...");                 	  
	          }			  
		  
	  
	  }
	  
	  public static void toggleRemainingTimeView()
	  {
		   if(!sBatteryStatus.equals("Charging") && !sBatteryStatus.equals("Discharging") 
				   ||(highNotificationLevel==level)
				   ||(lowNotificationLevel==level)
				   )
		   {
			   Log.i("TI", "Entered Invisible Condition");
		      	  remainingTime.setText("");  			   
		      	  remainingTime.setVisibility(View.INVISIBLE);				   
		   }
		  
	  }
	
  
}

